<template>
  <div>
    <a-card :bordered="false" :bodyStyle="tstyle">
      <div class="table-page-search-wrapper">
        <a-form layout="inline">
          <a-row :gutter="48">
            <a-col :md="6" :sm="24">
              <a-form-item label="学院">
                <a-select
                  :disabled="this.collList.length === 1"
                  show-search
                  allowClear
                  placeholder="请选择所属学院"
                  v-model="queryParam.collegeId"
                  @change="changeCollege">
                  <a-select-option v-for="item of this.collList" :key="item.id">
                    {{ item.name }}
                  </a-select-option>
                </a-select>
              </a-form-item>
            </a-col>
            <a-col :md="6" :sm="24">
              <a-form-item label="开课学年">
                <a-select
                  show-search
                  allowClear
                  placeholder="请选择开课学年"
                  v-model="queryParam.schoolYearId"
                  @change="changeSchoolYear">
                  <a-select-option v-for="item of this.schoolYearList" :key="item.id">
                    {{ item.name }}
                  </a-select-option>
                </a-select>
              </a-form-item>
            </a-col>
            <a-col :md="6" :sm="24">
              <a-form-item label="开课学期">
                <a-select show-search allowClear placeholder="请选择开课学期" v-model="queryParam.termId">
                  <a-select-option v-for="item of this.schoolTermList" :key="item.id">
                    {{ item.name }}
                  </a-select-option>
                </a-select>
              </a-form-item>
            </a-col>

            <template v-if="advanced">
              <a-col :md="6" :sm="24">
                <a-form-item label="开课课程">
                  <a-select
                    show-search
                    allowClear
                    placeholder="请选择开课课程"
                    v-model="queryParam.courseId"
                    :disabled="!queryParam.collegeId">
                    <a-select-option v-for="item of this.courseList" :key="item.id">
                      {{ item.name }}
                    </a-select-option>
                  </a-select>
                </a-form-item>
              </a-col>

              <a-col :md="6" :sm="24">
                <a-form-item label="开课课程ID">
                  <a-input allowClear placeholder="请输入开课课程ID" v-model="queryParam.coursePublishId"/>
                </a-form-item>
              </a-col>
            </template>

            <a-col :md="6" :sm="24">
              <span class="table-page-search-submitButtons">
                <a-button type="primary" @click="$refs.table.refresh(true)">查询</a-button>
                <a-button style="margin-left: 8px" @click="resetParam">重置</a-button>
                <a @click="toggleAdvanced" style="margin-left: 8px">
                  {{ advanced ? '收起' : '展开' }}
                  <a-icon :type="advanced ? 'up' : 'down'"/>
                </a>
              </span>
            </a-col>
          </a-row>
        </a-form>
      </div>
    </a-card>
    <a-card :bordered="false">
      <s-table ref="table" :columns="columns" :data="loadData" :rowKey="(record) => record.id">
        <template class="table-operator" slot="operator">
          <a-button type="primary" icon="plus" @click="$refs.choose.open(undefined)">新增排课</a-button>
        </template>
        <span slot="state" slot-scope="text, record">
          <a-tag color="red" v-if="record.state === 0">待发布</a-tag>
          <a-tag color="green" v-if="record.state === 1">已发布</a-tag>
        </span>
        <span slot="frequencyIndex" slot-scope="text, record">
          {{
            record.frequencyIndex
              ? record.frequencyIndex
                .split(',')
                .map((item) => `第${item}轮`)
                .join()
              : ''
          }}
        </span>
        <span slot="dayOfWeek" slot-scope="text, record">
          {{
            record.dayOfWeek
              ? record.dayOfWeek
                .split(',')
                .sort()
                .map((item) => `周${['一', '二', '三', '四', '五'][item - 1]}`)
                .join()
              : ''
          }}
        </span>

        <span slot="publishState" slot-scope="text, record">
          <a-tag color="red" v-if="record.publishState === 0">待发布</a-tag>
          <a-tag color="green" v-if="record.publishState === 1">已发布</a-tag>
        </span>

        <span slot="action" slot-scope="text, record">
          <a @click="$refs.detail.open(record)">编辑</a>

          <a-divider type="vertical"/>

          <a @click="$refs.detail.open(record, true)">查询</a>

          <a-divider type="vertical" v-if="record.state ===0"/>
          <a-popconfirm
            placement="topLeft"
            title="确认发布？【开课课程一旦发布，除“实验人数“外其他信息不可编辑。】"
            @confirm="() => publishCourseSchedule(record)"
            v-if="record.state ===0"
          >
            <a>发布</a>
          </a-popconfirm>

          <a-divider type="vertical" v-if="record.state ===1"/>
          <a-popconfirm
            placement="topRight"
            title="确认撤回？"
            @confirm="() => rollbackCourseSchedule(record.id)"
            v-if="record.state ===1"
          >
            <a>撤回</a>
          </a-popconfirm>

          <a-divider type="vertical" v-if="record.state ===0"/>

          <a-popconfirm
            placement="topRight"
            title="确认删除？"
            @confirm="() => singleDelete(record)"
            v-if="record.state ===0">
            <a>删除</a>
          </a-popconfirm>
        </span>
      </s-table>
      <course-schedule-detail ref="detail" @ok="handleOk"/>
      <course-publish-choosen ref="choose" @ok="chooseOK"/>
    </a-card>
  </div>
</template>
<script>
  import { STable, XDown } from '@/components'
  import {
    courseSchedulePageWithName,
    courseScheduleDelete,
    courseSchedulePublish,
    courseScheduleRollback
  } from '@/api/modular/main/courseScheduleManage'
  import CourseScheduleDetail from './detail.vue'
  import CoursePublishChoosen from './choose.vue'
  import { sysCollegeList } from '@/api/modular/system/sysCollegeManage'
  import { sysSchoolYearList } from '@/api/modular/system/sysSchoolYearManage'
  import { sysSchoolTermList } from '@/api/modular/system/sysSchoolTermManage'
  import { courseList } from '@/api/modular/system/courseManage'

  export default {
    components: {
      STable,
      CourseScheduleDetail,
      CoursePublishChoosen,
      XDown
    },
    data() {
      return {
        // 高级搜索 展开/关闭
        advanced: false,
        // 查询参数
        queryParam: {
          collegeId: undefined,
          courseId: undefined,
          termId: undefined,
          schoolYearId: undefined,
          coursePublishId: undefined
        },
        courseList: [],
        collList: [],
        schoolYearList: [],
        schoolTermList: [],
        // 表头
        columns: [
          {
            title: '院系',
            align: 'center',
            dataIndex: 'collegeName'
          },
          {
            title: '开课课程ID',
            align: 'center',
            dataIndex: 'coursePublishId'
          },
          {
            title: '开课课程',
            align: 'center',
            dataIndex: 'courseName'
          },
          {
            title: '开课学年',
            align: 'center',
            dataIndex: 'schoolYearName'
          },
          {
            title: '开课学期',
            align: 'center',
            dataIndex: 'termName'
          },
          {
            title: '开课状态',
            align: 'center',
            dataIndex: 'publishState',
            scopedSlots: { customRender: 'publishState' }
          },
          {
            title: '开课模块',
            align: 'center',
            dataIndex: 'moduleName'
          },
          {
            title: '实验项目',
            align: 'center',
            dataIndex: 'projectName'
          },
          {
            title: '实验老师',
            align: 'center',
            dataIndex: 'teacherName'
          },
          {
            title: '实验教室',
            align: 'center',
            dataIndex: 'classroomName'
          },
          {
            title: '排课轮次',
            align: 'center',
            dataIndex: 'frequencyIndex',
            scopedSlots: { customRender: 'frequencyIndex' }
          },
          {
            title: '排课日期',
            align: 'center',
            dataIndex: 'dayOfWeek',
            scopedSlots: { customRender: 'dayOfWeek' }
          },
          {
            title: '排课状态',
            align: 'center',
            dataIndex: 'state',
            scopedSlots: { customRender: 'state' }
          }
        ],
        tstyle: { 'padding-bottom': '0px', 'margin-bottom': '10px' },
        // 加载数据方法 必须为 Promise 对象
        loadData: (parameter) => {
          return courseSchedulePageWithName(Object.assign(parameter, this.queryParam)).then((res) => {
            return res.data
          })
        }
      }
    },
    created() {
      this.getCollList()
      this.getSchoolYearList()
      this.getSchoolTermList()
      this.columns.push({
        title: '操作',
        width: '180px',
        dataIndex: 'action',
        align: 'center',
        scopedSlots: { customRender: 'action' }
      })
    },
    watch: {
      $route: {
        handler(val) {
          if (val.name === 'CourseSchedule') {
            const params = this.$route.params
            if (params.collegeId === undefined || params.collegeId === null) return
            setTimeout(() => {
              this.$refs.detail.openAndCreate(params)
            }, 1000)
          }
        },
        immediate: true
      }
    },
    methods: {
      toggleAdvanced() {
        this.advanced = !this.advanced
      },
      /**
       * load学院列表
       */
      getCollList() {
        sysCollegeList().then((res) => {
          if (res.success) {
            this.collList = res.data
            if (this.collList.length === 1) {
              // 如果只有一条，默认选上
              this.queryParam.collegeId = this.collList[0].id
              this.getCourseList()
            }
          }
        })
      },
      /**
       * load学年列表
       */
      getSchoolYearList() {
        sysSchoolYearList().then((res) => {
          if (res.success) {
            this.schoolYearList = res.data
          }
        })
      },
      /**
       * load开课学期
       */
      getSchoolTermList(schoolYearId) {
        sysSchoolTermList({
          schoolYearId: schoolYearId
        }).then((res) => {
          if (res.success) {
            this.schoolTermList = res.data
          }
        })
      },
      /**
       * load课程
       */
      getCourseList() {
        courseList({
          collId: this.queryParam.collegeId
        }).then((res) => {
          if (res.success) {
            this.courseList = res.data
          }
        })
      },
      changeCollege() {
        this.queryParam.courseId = undefined
        this.getCourseList()
      },
      /**
       * 单个删除
       */
      singleDelete(record) {
        const param = [{ id: record.id }]
        courseScheduleDelete(param).then((res) => {
          if (res.success) {
            this.$message.success('删除成功')
            this.$refs.table.clearRefreshSelected()
          } else {
            this.$message.error('删除失败') // + res.message
          }
        })
      },
      handleOk() {
        this.$refs.table.refresh()
      },
      chooseOK(coursePublish) {
        // console.log(coursePublish)
        this.$refs.detail.openAndCreate(coursePublish)
      },
      /**
       * 发布
       */
      publishCourseSchedule(record) {
        if (record.teacherId === null) {
          this.$message.error('实验老师不能为空')
          return
        }
        if (record.classroomId === null) {
          this.$message.error('实验教室不能为空')
          return
        }
        if (record.maxStudents === null) {
          this.$message.error('最大人数不能为空')
          return
        }
        courseSchedulePublish(record.id).then((res) => {
          if (res.success) {
            this.$message.success('发布成功')
            this.$refs.table.refresh()
          } else {
            this.$message.error('发布失败：' + res.message)
          }
        })
      },
      /**
       * 撤回
       */
      rollbackCourseSchedule(courseScheduleId) {
        courseScheduleRollback(courseScheduleId).then((res) => {
          if (res.success) {
            this.$message.success('撤回成功')
            this.$refs.table.refresh()
          } else {
            this.$message.error('撤回失败：' + res.message)
          }
        })
      },
      resetParam() {
        if (this.collList.length === 1) {
          this.queryParam = {
            ...this.queryParam,
            courseId: undefined,
            termId: undefined,
            schoolYearId: undefined,
            coursePublishId: undefined
          }
        } else {
          this.queryParam = {
            collegeId: undefined,
            courseId: undefined,
            termId: undefined,
            schoolYearId: undefined,
            coursePublishId: undefined
          }
        }
      },
      changeSchoolYear(schoolYearId) {
        this.queryParam.termId = undefined
        this.getSchoolTermList(schoolYearId)
      }
    }
  }
</script>
<style lang="less">
  .table-operator {
    margin-bottom: 18px;
  }

  button {
    margin-right: 8px;
  }
</style>
